package org.moore.controller;

import org.moore.model.User;
import org.moore.utils.UserUtils;
import org.moore.view.WelcomePanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class YesRegisterButtonListener implements MouseListener {
    private final WelcomePanel welcomePanel;

    public YesRegisterButtonListener(WelcomePanel welcomePanel) {
        this.welcomePanel = welcomePanel;
    }

    // 确认注册监听类
    @Override
    public void mouseClicked(MouseEvent e) {
        // 创建一个新的字体对象
        Font newFont = new Font("宋体", Font.PLAIN, 18);
        // 设置所有的OptionPane字体
        UIManager.put("OptionPane.messageFont", newFont);
        UIManager.put("OptionPane.buttonFont", newFont);
        // 获取文本内容
        String acc = WelcomePanel.getRegisterJLabel().getAccText().getText().trim();
        String pwd = new String(WelcomePanel.getRegisterJLabel().getPwdText().getPassword()).trim();
        String againPwd = new String(WelcomePanel.getRegisterJLabel().getPwdAgainText().getPassword()).trim();
        String name = WelcomePanel.getRegisterJLabel().getNameText().getText().trim();
        int id = WelcomePanel.getRegisterJLabel().getId();

        // 非空判断
        if (acc.isEmpty() || pwd.isEmpty() || againPwd.isEmpty()) {
            JOptionPane.showMessageDialog(welcomePanel, "账号或密码不得为空");
            return;
        }

        // 昵称是否设置
        if (name.isEmpty()) {
            int panel = JOptionPane.showConfirmDialog(welcomePanel, "您未设置昵称，将使用玩家id作为您的昵称，确定吗？");
            if (panel == 0) {
                name = Integer.toString(id);
            } else if (panel == 1) {
                JOptionPane.showMessageDialog(welcomePanel, "昵称不得为空，注册失败！");
                return;
            }
        }

        // 输入的密码与重复密码是否一致
        if (!pwd.equals(againPwd)) {
            JOptionPane.showMessageDialog(welcomePanel, "密码与重复密码不一致，请检查！");
            return;
        }

        // 检测账号是否存在，若否则添加用户
        if (UserUtils.findAccAndPwdByAdmin(acc, pwd) != null) {
            JOptionPane.showMessageDialog(welcomePanel, "账号已存在，请返回登录！");
        } else {
            UserUtils.insertAdmin(new User(id, acc, pwd, name));
            JOptionPane.showMessageDialog(welcomePanel, "注册成功！将返回登录！");
            // 返回登录界面
            WelcomePanel.getCardLayout().show(welcomePanel, "Login");
        }
    }


    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
